package com.remoter.context.spring.bean;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import com.remoter.basic.bean.support.ConsumerModule;
import com.remoter.basic.configure.IConfiguration;
import com.remoter.basic.configure.support.AbstractConfiguration;
import com.remoter.basic.context.IContext;
import com.remoter.basic.util.Final;
import com.remoter.basic.util.ServiceLoader;

/**
 * @author			koko
 * @date 			2017-08-09 16:37:39
 * @description 	类功能说明
 */
public class ConsumerBean extends ConsumerModule implements FactoryBean<Object>,ApplicationContextAware,InitializingBean,DisposableBean{
	
	private static final long serialVersionUID = -8568422544619926220L;
	private static final Logger logger = LoggerFactory.getLogger(ProviderBean.class);
	
	private static IContext context;
	
	private Class<?> service;
	private ConsumerModule module;
	
	public ConsumerBean(String name,Class<?> type){
		try{
			this.setBean(name);
			this.setType(type.getName());
			this.service = type;
			IConfiguration configuration = AbstractConfiguration.getConfiguration();
			context = ServiceLoader.getService(IContext.class,configuration.getOption(Final.O_VAL_CONTEXT));
			this.module = context.createConsumerModule(null);
			this.module.setBean(this.getBean());
			this.module.setType(this.getType());
			context.attachConsumer(this.service,this.module);
		}catch(Exception e){
			logger.error(e.getMessage(),e);
		}
	}
	
	@Override
	public void destroy() throws Exception {
		context.detachConsumerModule(this.module);
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		
	}

	@Override
	public Object getObject() throws Exception {
		return context.attachConsumer(this.service,this.module);
	}

	@Override
	public Class<?> getObjectType() {
		return this.service;
	}

	@Override
	public boolean isSingleton() {
		return true;
	}
	
}